package com.springboot.wisdom.mqtt.config;

import com.springboot.wisdom.mqtt.handler.ReceiverMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;


/**
 * mqtt通道配置类。
 */
@Configuration
public class MqttInboundConfiguration {

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;

    @Autowired
    private MqttPahoClientFactory mqttPahoClientFactory;

    @Autowired
    private ReceiverMessageHandler receiverMessageHandler;

    /**
     * 消息通道。
     * （接收消息: 步骤一）定义一个消息通道，用于接收消息。
     *
     * @return
     */
    @Bean
    public MessageChannel messageInboundChannel() {
        return new DirectChannel();
    }

    /**
     * 配置入站适配器，设置订阅主题，以及指定消息的相关属性。
     * （接收消息:步骤二）配置消息驱动通道适配器，用于接收指定主题的消息。
     *
     * @return
     */
    @Bean
    public MessageProducer messageProducer() {
        MqttPahoMessageDrivenChannelAdapter adapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttConfigurationProperties.getUrl(),
                mqttConfigurationProperties.getSubClientId(),
                mqttPahoClientFactory,
                mqttConfigurationProperties.getSubTopic().split(",")
        );
        adapter.setQos(1);
        adapter.setConverter(new DefaultPahoMessageConverter());
        adapter.setOutputChannel(messageInboundChannel());
        return adapter;
    }

    /**
     * 配置订阅的主题。
     * （接收消息:步骤三）配置消息处理器，用于处理接收到的消息。
     *
     * @return
     */
    @Bean
    @ServiceActivator(inputChannel = "messageInboundChannel")
    public MessageHandler messageHandler() {
        return receiverMessageHandler;
    }

}
